<template>
    <homeBase @update_patient="update_patient" btn_text="添加看病记录" select_date_isShow="true" >
        <template v-slot:title>
            <p >看病记录查询</p>
        </template>
        <!-- <search /> -->
        <template v-slot:container>
            <div class="patient-info">
            <div>
                <table class="patient-data" v-if="show_list">
                <tr class="header"><td>病历号</td><td>就诊时间</td><td>姓名</td><td>性别</td><td>医保类型</td><td>就诊医生</td><td>病历描述（症状）</td><td>所用处方id</td><td>治疗结果</td></tr>
                <tr v-for = "(item,index) in show_list" @click="current_medical_record(item,index,$event)" :class="{select:index==medical_record_index}">
                    <td id="id">{{ item.id }}</td>
                    <td id="treat_time">{{ item.treat_time }}</td>
                    <td id="patient_name">{{ item.patient_name }}</td>
                    <td id="gender">{{ item.patient_gender }}</td>
                    <td id="medical_insurance">{{ item.medical_insurance }}</td>
                    <td id="docter_name">{{ item.docter_name }}</td>
                    <td id="symptom_description">{{ item.symptom_description }}</td>
                    <td id="prescription">{{ item.prescription }}</td>
                    <td id="treatment_results">{{ item.treatment_results }}</td>
                    </tr>
                </table>
                <div class="pager">
                    <a href="javascript:;" @click="next_page(-1)">上一页</a>
                    <a :class="{active: current_page+1 == item}" href="javascript:;" @click="click_page(item)" v-for="(item,index) in total_page">{{ item }}</a>
                    <a v-if="treat_record_more=='yes'" href="javascript:;" @click="click_more_page(item)">...</a>
                    <a v-if=" !(this.total_page==this.current_page+1 && this.treat_record_more=='no') " href="javascript:;" @click="next_page(1)">下一页</a>
                </div>
            </div>
            <div class="button" v-if="show_list">
                <button class="edit" @click="show_details($event)">{{ button_text }}</button>
                <button v-show="submitShow" class="submit" @click="submit">提交</button>
            </div>
            </div>
        </template>
        
        
    </homeBase>
</template>

<script>
import homeBase from '@/components/home/homeBase.vue'
export default {
    props:['title'],
    data(){
        return{
            submitShow:false,
            button_text:'查看详情',
            medical_record_item:null,
            medical_record_index:null,
            show_list:null,
            new_patient:{},
            medical_record_y:null,  // 当前选择的病历项相对于父元素(或者是他的容器)的y坐标
            server_return_max_size:120,  // 服务器一次性最多返回120条记录
            server_return_max_page:null,  // 服务器一次性最多返回多少页
            reques_count:0,  // 当前是第几次请求，从0开始
            current_page:0,  // 当前页面
            total_page:1,  // 目前的总页数
            page_size:15,  // 每页显示的数量，暂定15条记录
            treat_record_more:null,  // 是否还有更多病历
        }
    },
    components:{
        homeBase
    },
    methods:{
        show_details(){
            // 根据病人id来查看病历信息
            if(this.medical_record_item==null){
                this.$toast("请先选择你要查看的病历")
                return
            }

            // this.$router.push(`/treat_record_details/${this.medical_record_item.patient_id}`)

            this.$router.push({
                path:'/treat_record_details',
                query:{
                    patient_index:this.reques_count,
                    patient_id:this.medical_record_item.patient_id,
                    m_r_id:this.medical_record_item.id
                }
            })

        },
        edit(e){
            let el = document.querySelectorAll(".value")
            if(this.button_text=='编辑信息'){
                this.button_text='取消'
                this.submitShow=!this.submitShow
                el.forEach(item=>{
                    item.setAttribute("contentEditable",this.submitShow)
                })
                el[0].focus()
            }else{
                this.button_text='编辑信息'
                this.submitShow=!this.submitShow
                this.update_patient()
                el.forEach(item=>{
                    item.setAttribute("contentEditable",this.submitShow)
                })
            }
        },
        add_medical_record(){
            let promise = new Promise((resolve,reject)=>{
                // 这是一个异步函数，先添加数据，需要用异步函数才能改变它对应的dom元素属性
                let time = new Date().toLocaleDateString().replace(/\//g,"-")
                this.patient.medical_record.push([time,""])
                resolve("ok")
            }).then(msg=>{
                let el = document.querySelectorAll(".value")
                el.forEach(item=>{
                    item.setAttribute("contentEditable",this.submitShow)
                })
            })
        },
        del_medical_record(){  // 删除病历
            if(this.medical_record_item==null){
                this.$toast.fail("请先点击要删除的病历")
                return
            }
            this.patient.medical_record.splice(this.medical_record_item,1)
            this.medical_record_item=null
        },
        current_medical_record(item,index,el){  // 记录当前选择的病历
            // this.medical_record_item=item
            // this.medical_record_index=index
            // this.$store.state.global_var.select_treat_record={
            //     item:item,
            //     index:index
            // }  // 全局保存下

            this.medical_record_item=item
            this.medical_record_index=index
            this.$store.state.global_var.select_treat_record={
                item:item,
                index:index
            }  // 全局保存下
            let e = el.currentTarget
            this.medical_record_y = e.offsetTop
            let edit = document.querySelector(".edit")
            edit.style.marginTop=this.medical_record_y+5+"px"
        },
        td_change(el,index,num){  // 输入病历信息后，保存病历信息
            if(num==0){
                this.patient.medical_record[index].splice(0,1,el.currentTarget.innerText)
            }else if(num==1){
                this.patient.medical_record[index].splice(1,1,el.currentTarget.innerText)
            }
        },
        td_change1(e){  // 保存基本资料
            let el = e.currentTarget
            let id = e.currentTarget.getAttribute("id")
            this.patient[id]=el.innerText.trim()
        },
        next_page(n){  // 点击下一页时获取数据
            
            this.current_page+=n
            if(this.current_page<0){
                this.current_page=0
            }
            let edit = document.querySelector(".edit")
            edit.style.marginTop="0px"
            // console.log(this.current_page);
            // 目前的做法是，后端一次性返回server_return_max_size条记录，前端默认每页显示15条，如果查出来的结果还有多的就再向后端发送请求
            // 计算出当前的请求次数，请求过的内容可以不用再请求
            this.reques_count = Math.floor(this.current_page/(this.server_return_max_size/this.page_size))
            if(this.current_page%(this.server_return_max_size/this.page_size)==0 && n==1 && !this.$store.state.show_list[this.reques_count]){
                // 如果当前的请求刚好超过了要显示的类容，并且用户点击的是下一页，并且全局变量里没有对应的数据，那说明该向后端发送请求了，
                let search = this.$store.state.global_var.search
                // this.$refs.homeBase.search(search.patient,this.current_page)
                this.$http({
                    method:'post',
                    url:'/ajax/api/search_patient',
                    data:{
                        patient:search.patient,
                        date:search.date,
                        current_page:this.current_page || 0,
                        page_size:this.page_size
                    }
                }).then(data=>{
                    if(typeof data.data == "string"){
                        this.$toast(data.data)
                        return
                    }
                    console.log(data.data);
                    this.next_page_arrange_data(data)
                    this.update_patient()
                })
            }else{
                this.update_patient()
            }
        },
        // 数据整理
        next_page_arrange_data(data){
            // 获取到数据后，保存数据
            if (data.data.treat_record_more=="yes"){
                data.data.treat_record=data.data.treat_record.slice(0,this.server_return_max_size)
            }
            if (data.data.treat_record_more=="yes"){
                data.data.treat_record=data.data.treat_record.slice(0,this.server_return_max_size)
            }
            // 如果用户是按日期查询数据的话，要对数据进行整理
            data.data.patient_list.forEach((item,index)=>{
                data.data.patient_list[index].medical_record=[]
                data.data.patient_list[index].treat_record=[]
                // 根据生日，计算出年龄
                data.data.patient_list[index]["age"]= this.$my_tools.getAge(item["birthday"])
                data.data.medical_record.forEach((m_item,m_index)=>{
                    if (item.id==m_item.patient_id){
                        data.data.patient_list[index].medical_record.push(m_item)
                        // this.$store.state.show_list.medical_record[m_index].medical_insurance=item.medical_insurance
                    }
                })
                data.data.treat_record.forEach((m_item,m_index)=>{
                    if (item.id==m_item.patient_id){
                        data.data.patient_list[index].treat_record.push(m_item)
                    }
                })
            })
            let index=Math.floor(this.current_page/(this.server_return_max_size/this.page_size))
            this.$store.state.show_list[index] = data.data
            this.$store.state.patient[index] = data.data.patient_list
            this.$store.state.global_var.current_page=data.data.current_page
        },
        // 用户直接点击页数时
        click_page(current_page){
            this.current_page = current_page
            this.next_page(-1)
        },
        click_more_page(){
            this.current_page = this.total_page-1
            this.next_page(1)
        },
        check_data(){  // 检查输入的信息是否正确
            for (let item in this.patient){
                if(this.$my_tools.check_data[item]){ 
                    let msg=this.$my_tools.check_data[item](this.patient[item])
                    if(msg){
                        this.$toast(msg)
                        return false
                    }
                }
            }
        },
        submit(){  // 提交新病人信息
            if(this.check_data()==false){
                return
            }
            // document.querySelectorAll(".edit")[0].innerText="编辑信息"
            this.button_text='编辑信息'
            this.submitShow=false
            let values = document.querySelectorAll(".value")
            values.forEach((item,index)=>{
                item.setAttribute("contentEditable",this.submitShow)
            })
            // 发送ajax请求，保存数据
            // let xmlhttp=new XMLHttpRequest();
            // xmlhttp.open("post","ajax/api/edit_patient",true);
            // xmlhttp.send(this.patient);
            // console.log(xmlhttp.responseText);
            // let params = qs.stringify(this.patient)
            // let params = JSON.stringify(this.patient)
            this.$http({
                method:'post',
                url:'ajax/api/edit_patient',
                data:{
                    patient:this.patient
                }
            }).then(data=>{
                if(data.data=="ok"){
                    this.$toast.success("编辑成功")
                    this.$store.state.patient[0] =this.$my_tools.deepClone(this.patient)
                    // this.$http({
                    //     method:'post',
                    //     url:'/ajax/api/search_patient',
                    //     data:{
                    //         patient:{name:this.patient.name}
                    //     }
                    // }).then(data=>{
                    //     this.$store.state.patient = data.data
                    //     this.patient=this.$store.state.patient[0]
                    //     // if(this.$route.path=="/add_patient"){
                    //     //     this.$router.push("/patientInfo")
                    //     // }
                    // })

                }else{
                    this.$toast.fail("编辑失败，发生未知错误")
                }
            })

            
        },
        update_patient(){
            // 获取当前页面需要的数据
            
            if(this.$store.state.global_var.current_page==0 ){
                // 如果搜索的内容发生了变化，则重置当前页和总页数
                this.$store.state.global_var.current_page=null
                this.current_page=0  // 重置当前页
                // this.current_page=this.$store.state.show_list[0].current_page  
                this.total_page=this.current_page + Math.ceil(this.$store.state.show_list[0].treat_record.length/this.page_size)  // 计算出总共有多少页
                this.update_patient()
            }
            let index=Math.floor(this.current_page/(this.server_return_max_size/this.page_size))
            this.total_page =Math.ceil((this.$store.state.show_list[index].treat_record.length)/this.page_size)+index*this.server_return_max_page
            this.show_list = this.$my_tools.deepClone(this.$store.state.show_list[index].treat_record.slice((this.current_page%this.server_return_max_page)*this.page_size,(this.current_page%this.server_return_max_page+1)*this.page_size))
            this.treat_record_more = this.$store.state.show_list[index].treat_record_more
            // console.log(this.show_list);
        },
    },
    computed:{
        next_page_show(){
            if(this.total_page==this.current_page+1 && this.medical_record_more=="no"){
                return false
            }else{
                return true
            }
        }
    },
    mounted(){
        // 计算出服务器一次性最多返回的页数
        this.server_return_max_page=this.server_return_max_size/this.page_size
        if(this.$store.state.show_list.length>0){
            // this.show_list = this.$my_tools.deepClone(this.$store.state.show_list.medical_record.slice(this.current_page*this.page_size,(this.current_page+1)*this.page_size))
            this.update_patient()
        }else{
            this.show_list=[]
            this.$refs.homeBase.search({})
        }
        // if(this.$store.state.global_var.select_treat_record){
        //     this.medical_record_item = this.$store.state.global_var.select_treat_record.item
        //     this.medical_record_index = this.$store.state.global_var.select_treat_record.index
        // }
    }
}
</script>

<style lang='scss' scoped>
.patient-info{
    border: 1px solid #ccc;
    // width: 90%;
    height: 80%;
    margin-top: 5px;
    padding: 5px;
    overflow: auto;
    display: flex;
    align-items: flex-start;
    // 表格样式
    table{
        flex:0 0 auto;
    }
    table,tr,td{
        border: 1px solid #aaa;
        vertical-align: middle;
        
    }
    td{
        padding: 8px;
        max-width: 150px;
        white-space: nowrap;
        overflow: hidden;
    }
    tr{
        background-color: rgb(253, 255, 250);
    }
    .header{
        font-weight: bolder;
        background-color: rgb(213, 219, 203);
        // td{
        //     overflow: hidden;
        //     resize: horizontal;
        // }
    }
    .key{
        font-weight: bolder;
        width: 100px;
    }
    .value{
        width: 200px;
        word-break: break-all;
    }
    .button{
        display: flex;
        margin-left: 10px;
        // flex:1;
        flex-direction: column;
        button{
            margin-bottom: 10px;
        }
    }
    .center{
        font-weight: bolder;
        // text-align: center;
    }
    .spare{
        font-size: 20px;
        font-weight: bolder;
        margin: 50px auto;
    }
    .select{
        background-color: rgb(233, 235, 230);
    }
    .pager{
        // width: 200px;
        margin: 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        a{
            margin:0 5px;
            // color:rgb(105, 119, 243);
        }
        .active{
            color:black;
            cursor:default;
            font-weight: bolder;
            font-size: 20px;
        }
    }
}
</style>